package utils

import (
	"time"

	"github.com/golang-jwt/jwt"
	"github.com/spf13/viper"
)

type TokenInfo struct {
	ID         int
	UpdateTime int64
}
type MyClaims struct {
	TokenInfo *TokenInfo
	jwt.StandardClaims
}

var signingKey = []byte(viper.GetString("jwt.signingKey"))
var issuer = []byte(viper.GetString("jwt.issuer"))

func CreateJwt(tokenInfo TokenInfo) (token string, error error) {
	token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, MyClaims{
		TokenInfo: &tokenInfo,
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix(),            //多久开始生效
			ExpiresAt: time.Now().Unix() + 60*60*24, //过期时间
			Issuer:    string(issuer),
		},
	}).SignedString(signingKey)
	if err != nil {
		return "", err
	}
	return token, nil
}

func ParseJwt(token string) (*MyClaims, error) {
	info, err := jwt.ParseWithClaims(token, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return signingKey, nil
	})
	if err != nil {
		return nil, err
	}
	claims := info.Claims.(*MyClaims)
	return claims, nil
}
